namespace Engine.FileFormats3D.C11Syndikat.QADFile
{
    internal struct ObjectName
    {
        #region Private Fields

        private byte[] chars;
        private int hashcode;

        #endregion Private Fields

        #region Public Constructors

        public ObjectName(string name)
            : this(name.ToCharArray())
        { }

        public ObjectName(char[] chars)
        {
            this.chars = new byte[32];
            this.chars.Initialize();

            //char[] chars = textureName.ToCharArray();
            for (int i = 0; i < 32; i++)
            {
                if (i < chars.Length)
                    this.chars[i] = (byte)chars[i];
                else
                    this.chars[i] = 0x00;
            }

            this.hashcode = 0;
            UpdateHashcode();
        }

        #endregion Public Constructors

        #region Internal Constructors

        internal ObjectName(byte[] name)
        {
            this.chars = name;
            this.hashcode = 0;
            UpdateHashcode();
            return;
        }

        #endregion Internal Constructors

        #region Public Properties

        public byte[] Chars { get { return chars; } set { chars = value; } }

        #endregion Public Properties

        #region Public Methods

        public override int GetHashCode()
        {
            return this.hashcode;
        }

        public override string ToString()
        {
            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();

            string test = enc.GetString(chars);
            string[] splittet = test.Split("\0".ToCharArray());
            return splittet[0];
        }

        #endregion Public Methods

        #region Internal Methods

        internal static ObjectName FromStream(System.IO.BinaryReader br)
        {
            return new ObjectName(br.ReadBytes(32));
        }

        internal void Save(System.IO.BinaryWriter bw)
        {
            bw.Write(this.chars);
        }

        #endregion Internal Methods

        #region Private Methods

        private void UpdateHashcode()
        {
            AdlerChecksum adler = new AdlerChecksum();
            adler.MakeForBuff(this.chars);
            this.hashcode = (int)adler.ChecksumValue;
        }

        #endregion Private Methods
    }
}